<template>
    <div id="container"></div>
</template>

<script setup lang="ts">
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { onMounted  } from 'vue';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

onMounted(() => { 
    const renderer = new THREE.WebGLRenderer();
    document.getElementById('container')?.appendChild(renderer.domElement);
    renderer.setSize(window.innerWidth, window.innerHeight,false);
    renderer.domElement.width = window.innerWidth;
    renderer.domElement.height = window.innerHeight;
    
    const scene = new THREE.Scene();
    const lighting = new THREE.AmbientLight(0xffffff);
    scene.add(lighting);

    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight,0.1, 2000)
    // camera.position.set(0,0,500);
    // camera.lookAt(0,0,0);

    const controls = new OrbitControls(camera, renderer.domElement);

    const loader = new GLTFLoader();
    loader.load('/models/Horse.glb', function (gltf) { 
        console.log("加载成功",gltf);
        scene.add(gltf.scene);

        let mixer:any = null;

         // 1. 检查是否有动画
        if (gltf.animations && gltf.animations.length) {
            console.log("找到动画:", gltf.animations);
            
            // 2. 创建动画混合器
            mixer = new THREE.AnimationMixer(gltf.scene);
            
            // 3. 播放所有动画（或选择特定动画）
            gltf.animations.forEach((clip) => {
                mixer.clipAction(clip).play();
            });
        }

        // 自动计算模型大小并调整相机
        const box = new THREE.Box3().setFromObject(gltf.scene);
        const size = box.getSize(new THREE.Vector3()).length();
        const center = box.getCenter(new THREE.Vector3());
        
        camera.position.copy(center);
        camera.position.x += size * 0.5;
        camera.position.y += size * 0.5;
        camera.position.z += size * 1;
        camera.lookAt(center);
        
        // 更新控制器目标
        controls.target.copy(center);
        controls.update();

        let clock = new THREE.Clock();
        const animation = function () { 
            requestAnimationFrame(animation);
            controls.update();

            const delta = clock.getDelta(); 
            if (mixer) mixer.update(delta*2);  //更新模型动画

            renderer.render(scene, camera);
        };

        animation();

        window.onresize = function () {
            renderer.setSize(window.innerWidth, window.innerHeight);
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
        };
    },undefined,function (error) { 
        console.error(error);
    });

    renderer.render(scene, camera);
})

</script>

<style scoped>

</style>